//
//  YiAddServerListView.swift
//  yiplayer
//
//  Created by wkun on 2024/6/14.
//

import Foundation

class YiAddServerListView : YiListView, UITextFieldDelegate, DSKeyboardDelegate {
    var type: ServerType?
    var keyboard = DSKeyboard()
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.keyboard.delegate = self
        self.keyboard.addObserverKeyBoard()
        
        self.navView.rightBtn.img("check")
        self.navView.titleL.text = "添加服务器"
        
        self.tableView.keyboardDismissMode = .interactiveWithAccessory
        self.registerCell()
        self.loadDatas()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit{
        self.keyboard.removeObserver()
    }
    
    func loadDatas() {
        let tis = ["标题","主机","用户","密码","路径"]
        let phs = ["可选","必填","必填","必填","可选"]
        var ar = [YiAddServerListModel]()
        for i in 0..<tis.count {
            let m = YiAddServerListModel()
            m.title = tis[i]+":"
            m.placeHolder = phs[i]
            m.keyboardType = .default
            if i == 1 {
                m.keyboardType = .decimalPad
            }
            ar.append(m)
        }
        self.datas = ar
        self.tableView.reloadData()
    }
    
    override func registerCell() {
        self.tableView.register(YiAddServerListCell.self, forCellReuseIdentifier: self.reuseid)
    }
    
    // MARK: - Private
    func getValue(_ idx: Int) -> String {
        let m = self.model(datas, idx) as? YiAddServerListModel
        return m?.value ?? ""
    }
    
    // MARK: - TouchEvents
    override func handleNavRightBtn() {
        let title = self.getValue(0)
        let ip = self.getValue(1)
        let user = self.getValue(2)
        let pwd = self.getValue(3)
        let path = self.getValue(4)
        
        if ip.count == 0 || user.count == 0 || pwd.count == 0 {
            self.currCtrl()?.showErrorMsg("主机、用户、密码均不可为空")
            return
        }
        
        if self.type == nil {
            self.currCtrl()?.showErrorMsg("协议错误")
            return
        }
        
//    case smb = 1
//    case ftp = 2
//    case webdav = 3
        let imgdic = ["1":"net_smb", "2":"net_ftp", "3":"net_dav"]
        let ty = type!.rawValue
        let k = String(format: "%d", ty)
        let img = imgdic[k] ?? ""
        let ret = DB.addServer(name: title, ip: ip, path: path, username: user, pwd: pwd, type: ty, imgname: img, note: "")
        if ret {
            self.currCtrl()?.showSuccess("添加完成")
            DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
                
                if let ar = self.currCtrl()?.sublists {
                    for v in ar {
                        if let lv = v as? YiServerListView {
                            lv.loadDatas()
                        }
                    }
                }
                
                self.currCtrl()?.removeListView()
                Thread.sleep(forTimeInterval: 0.2)
                self.currCtrl()?.removeListView()
            }
        }else {
            self.currCtrl()?.showErrorMsg("添加失败")
        }
    }
    
    // MARK: - Delegate
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let c = super.tableView(tableView, cellForRowAt: indexPath)
        c.selectionStyle = .none
        if let c = c as? YiAddServerListCell {
            c.inputTf.tag = indexPath.row
            c.inputTf.delegate = self
        }
        return c
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        super.tableView(tableView, didSelectRowAt: indexPath)
        
        if let c = self.tableView.cellForRow(at: indexPath) as? YiAddServerListCell {
            c.inputTf.becomeFirstResponder()
        }
    }
    
    // MARK: - UITextFieldDelegate
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        self.keyboard.textField = textField
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        let i = textField.tag
        if let m = self.model(self.datas, i) as? YiAddServerListModel {
            m.value = textField.text
        }
    }
    
    // MARK: - KeyboardDelegate
    func keyBoardWillShow(_ keyBoard: DSKeyboard, keyBoardHeight height: CGFloat) {
        let op = self.containerView.convert(self.tableView.frame.origin, to: self)
        let h = self.frame.height - height - op.y
        self.tableView.makeCons { make in
            make.height.equal(h)
        }
    }
    
    func keyBoardDidShow(_ keyBoard: DSKeyboard) {
        if let i = keyBoard.textField?.tag {
            let ip = IndexPath.init(row: i, section: 0)
            self.tableView.scrollToRow(at: ip, at: .bottom, animated: true)
        }
    }
    
    func keyBoardWillHide(_ keyBoard: DSKeyboard, keyBoardHeight height: CGFloat) {
        let h = self.containerView.frame.height-self.tableView.frame.minY
        self.tableView.makeCons { make in
            make.height.equal(h)
        }
    }
}

class YiAddServerListModel: NSObject{
    var title: String?
    var placeHolder: String?
    var value: String?
    var keyboardType = UIKeyboardType.default
}

class YiAddServerListCell: YiListViewCell {
    let titleL = UILabel()
    let inputTf = UITextField()
    
    override var model: Any?{
        didSet{
            super.model = model
            
            if let m = model as? YiAddServerListModel {
                titleL.text = m.title
                inputTf.text = m.value
                inputTf.placeholder = m.placeHolder
                inputTf.keyboardType = m.keyboardType
                
                inputTf.attributedPlaceholder = .init(string: m.placeHolder ?? "", attributes: [.foregroundColor:UIColor.gray])
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.textL.removeFromSuperview()
        self.imgView.removeFromSuperview()
        
        titleL.pin(.w(50)).align(.right).font(14).color(ColorF)
        inputTf.font(14).color(ColorF)
        
        titleL.addTo(self.contentView).makeCons { make in
            make.left.top.bottom.equal(0)
        }
        
        inputTf.addTo(self.contentView).makeCons { make in
            make.left.equal(self.titleL).right.offset(10)
            make.top.bottom.equal(0)
            make.right.equal(-10)
        }
        
        inputTf.keyboardType = .numbersAndPunctuation
        
        self.contentView.bringSubviewToFront(self.line)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
